package com.fs.base.excel;

import com.alibaba.fastjson.JSONObject;
import com.fs.base.utils.ServletUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;

/**
 * Excel工具类
 * <p>Created by Raofeicheng on 2016-11-9.</p>
 * @author Raofeicheng
 * @version 1.0
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class ExcelUtils {

	/**
	 * 获取Excel配置
	 */
	public static ExcelOptions getOptions() {
		return getOptions(ServletUtils.getRequest());
	}

	/**
	 * 通过request获取Excel配置
	 */
	public static ExcelOptions getOptions(HttpServletRequest request) {
		return getOptions(request.getParameter("exportJson"));
	}

	/**
	 * 通过json解析获取Excel配置
	 */
	public static ExcelOptions getOptions(String json) {
		ExcelOptions opts = null;
		try {
			opts = JSONObject.parseObject(json, ExcelOptions.class);
		} catch (Exception e) {

		}
		if (null == opts) {
			opts = new ExcelOptions();
		}
		if (StringUtils.isNotBlank(opts.getFilename())) {
			opts.setFilename(getFilename(opts.getFilename()));
		}
		return opts;
	}

	/**
	 * 从获取Excel配置中获取文件名
	 */
	public static String getFilename(String filename) {
		Pattern pattern = Pattern.compile("(\\{date([:-_](.+)?)?\\})", Pattern.CASE_INSENSITIVE);
		Matcher matcher = pattern.matcher(filename);
		Date now = new Date();
		Map<String, String> map = new HashMap<String, String>();
		while (matcher.find()) {
			map.put(matcher.group(1), null != matcher.group(3) ? matcher.group(3) : "yyyy-MM-dd");
		}
		for (Map.Entry<String, String> entry : map.entrySet()) {
			filename = filename.replace(entry.getKey(), DateFormatUtils.format(now, entry.getValue()));
		}
		return filename;
	}

	public static String getColumnExcelName(int columnIndex) {
		if (columnIndex <= 0) {
			return null;
		}
		String columnStr = "";
		columnIndex--;
		do {
			if (columnStr.length() > 0) {
				columnIndex--;
			}
			columnStr = ((char) (columnIndex % 26 + (int) 'A')) + columnStr;
			columnIndex = (int) ((columnIndex - columnIndex % 26) / 26);
		} while (columnIndex > 0);
		return columnStr;
	}

}
